package com.chunuo.msmservice.controller;

import com.chunuo.commonutils.R;
import com.chunuo.msmservice.service.MsmService;
import com.chunuo.msmservice.utils.RandomUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 类的作用
 *
 * @author liujiamiao
 * @email 2544296058@qq.com
 * @date 2020-07-20 18:27
 */
@RestController
@RequestMapping("/smsservice/sms")
public class AliyunMsmController {

    @Autowired
    private MsmService msmService;

    @Autowired
    private RedisTemplate<Object, Object> redisTemplate;

    //发送短信的方法
    @GetMapping("send/{phone}")
    public R sendMsm(@PathVariable String phone) {
        Map<String,String> params = new HashMap<>();
        //从redis中获取验证码
        Object code = redisTemplate.opsForValue().get(phone);
        //如果验证码不存在，则需要获取验证码
        if(StringUtils.isEmpty(code)){
            //生成随机值，传递阿里云进行发送
            code = RandomUtil.getFourBitRandom();
        }
        //把验证码存到map中
        params.put("code",code.toString());

        //调用service发送短信的方法
        boolean isSend = msmService.send(params,phone);

        //判断是否发送成功
        if(isSend) {
            //发送成功，把发送成功验证码放到redis里面
            //设置有效时间
            redisTemplate.opsForValue().set(phone,code,5, TimeUnit.MINUTES);
            return R.ok();
        } else {
            return R.error().message("短信发送失败");
        }
    }

}
